package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.mapper.UserQuestionnaireMapper;
import com.rongke.model.Muser;
import com.rongke.model.Questionnaire;
import com.rongke.model.UserCondition;
import com.rongke.model.UserQuestionnaire;
import com.rongke.service.MuserService;
import com.rongke.service.QuestionnaireService;
import com.rongke.service.UserQuestionnaireService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.*;

/**
 * @UserQuestionnaireController
 * @用户问卷Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/userQuestionnaire")
@Transactional
@CrossOrigin
public class UserQuestionnaireController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private UserQuestionnaireService userQuestionnaireService;
    @Autowired
    private MuserService muserService;
    @Autowired
    private QuestionnaireService questionnaireService;

    /**
     * @添加用户问卷
     * @param userQuestionnaire
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addUserQuestionnaire(@RequestBody UserQuestionnaire userQuestionnaire){
        log.debug("添加用户问卷");
        userQuestionnaire.setGmtDatetime(new Date());
        userQuestionnaireService.insert(userQuestionnaire);
        return JsonResp.ok(userQuestionnaire);
    }

    /**
     * @修改用户问卷
     * @param userQuestionnaire
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateUserQuestionnaire(@RequestBody UserQuestionnaire userQuestionnaire){
        log.debug("修改用户问卷");
        userQuestionnaireService.updateById(userQuestionnaire);
        return JsonResp.ok(userQuestionnaire);
    }
    /**
     * @根据id查找用户问卷
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectUserQuestionnaire(Long id){
        log.debug("查找用户问卷");
        UserQuestionnaire userQuestionnaire = userQuestionnaireService.selectById(id);
        return JsonResp.ok(userQuestionnaire);
    }

    /**
     * @根据条件查找用户问卷
     * @param userQuestionnaire
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectUserQuestionnaireByCondition(@RequestBody UserQuestionnaire userQuestionnaire){
        log.debug("根据条件查找用户问卷");
        if(userQuestionnaire==null)
            return JsonResp.toFail("参数不能为空");
        List<UserQuestionnaire> userQuestionnaireList=userQuestionnaireService.selectByCondition(userQuestionnaire);
        return JsonResp.ok(userQuestionnaireList);
    }

    /**
     * 根据条件指定对象发布问卷
     *
     * @param condition
     * @param quId
     * @return
     */
    @RequestMapping(value = "/publishMsg4PartUsers", method = RequestMethod.POST)
    public JsonResp publishMsg4PartUsers(@RequestBody UserCondition condition, Long quId, String expireTime) {
        log.debug("根据条件指定对象发布问卷");
        if (null == quId)
            return JsonResp.toFail("参数不能为空");
        //获取推送用户id列表
        EntityWrapper<Muser> ewm = new EntityWrapper<>(condition.getMuser());
        ewm.isNotNull("user_name");
        ewm.setSqlSelect("id");
        if (condition.getMinAge() != null) {
            //大于最小年龄
            ewm.ge("(year(now())-year(birthday))", condition.getMinAge());
        }
        if (condition.getMaxAge() != null) {
            //小于最大年龄
            ewm.le("(year(now())-year(birthday))", condition.getMaxAge());
        }
        List<Object> ids = muserService.selectObjs(ewm);
        if (null != ids && !ids.isEmpty()) {
            Map map = new HashMap();
            map.put("quId", quId);
            map.put("userIds", ids);
            map.put("expireTime", expireTime);
//        long start=System.currentTimeMillis();
            userQuestionnaireService.insertBatchMsg(map);
//        long end=System.currentTimeMillis();
//        System.out.println("插入消息条数:"+ids.size());
//        System.out.println("执行时间"+(start-end)+"ms");
        }
    /*    Message msg=new Message(msgId);
        msg.setStatus(2);//设置消息状态为已发布
        msg.setUptDatetime(new Date());
        messageService.updateById(msg);*/
        return JsonResp.ok("发布用户问卷成功");
    }

    /**
     * 用户获取待填写的调查问卷列表
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getAvailableQuestionairesByUserId",method = RequestMethod.GET)
    public JsonResp getAvailableQuestionairesByUserId(Long userId){
        log.debug("用户获取待填写的调查问卷列表");
        if(null==userId){
            return JsonResp.toFail("参数不能为空");
        }
        //将已过期的状态修改为已过期
        EntityWrapper<UserQuestionnaire> ewu=new EntityWrapper<>();
        ewu.eq("status",1);
        ewu.eq("muser_id",userId);
        ewu.where("now()>expire_time ");
        List<UserQuestionnaire> expireLists=userQuestionnaireService.selectList(ewu);
        if(!expireLists.isEmpty()){
            expireLists.forEach(e->{
                e.setStatus(3);
            });
            userQuestionnaireService.updateBatchById(expireLists);
        }

        EntityWrapper<UserQuestionnaire> ew=new EntityWrapper<>();
        ew.in("status", Arrays.asList(1,2));
        ew.eq("muser_id",userId);
        List<UserQuestionnaire> lists=userQuestionnaireService.selectList(ew);
        lists.forEach(e->{
            Questionnaire qn=questionnaireService.selectById(e.getQuestionnaireId());
            e.setQuestionnaire(qn);
        });
        return JsonResp.ok(lists);
    }

}
